<template>
  <div>
    <van-form @submit="onSubmit">
      <van-field
        v-model="userInfo.username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[
          { required: true, message: '请填写用户名' },
          // { pattern: /\w{4,6}/, message: '请输入4到6位字符' }
          /*
          {
              validator: (value) => {
                // 只能输入小明
                if (value === '小明') {
                  return true
                } else {
                  return false
                }
              },
              message: '不要乱输入'}
              */
        ]"
      />
      <van-field
        v-model="userInfo.pwd"
        type="password"
        name="pwd"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
    <van-button @click="$router.push('/register')">去注册页</van-button>
  </div>
</template>

<script>
import { doLogin } from '_api'
import { Toast } from 'vant'
export default {
  name: 'login',
  data () {
    return {
      userInfo: {
        username: '',
        pwd: ''
      }
    }
  },
  methods: {
    onSubmit (params) {
      doLogin({
        ...params,
        deviceId: 11,
        deviceName: 'xxx'
      }).then(res => {
        if (res.data.code === 0) {
          // 将登录成功的token 缓存起来
          localStorage.setItem('token', res.data.data.token)
          Toast({
            type: 'success',
            message: '登录成功',
            onClose: () => {
              if (this.$route.query.from) {
                // 被拦截 进入登录页 回去
                this.$router.replace(this.$route.query.from)
              } else {
                this.$router.replace('/home')
              }
            }
          })
        } else {
          Toast.fail('登录失败')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
